from odoo import fields, models, api, _
from markupsafe import Markup


class WorkflowCheckWizard(models.TransientModel):
    _inherit = "workflow.check.wizard"

    def approval_pass(self):
        super(WorkflowCheckWizard, self).approval_pass()
        workflow = self.sb_workflow_item_id.sb_workflow_id
        if workflow.workflow_type == 'sale_change_apply' and workflow.state == 'approve':
            apply = workflow.sale_change_apply_id
            s_ = False
            if apply.sale_order_id.locked:
                # 解锁、再锁定
                apply.sale_order_id.locked = False
                s_ = True
            if apply.apply_type in ['change_status', 'change_design']:
                if apply.order_type == 'cancel':
                    apply.sale_order_id.action_unlock()
                    apply.sale_order_id.with_context(disable_cancel_warning=True, ecr_apply=True).action_cancel()
                    apply.sale_order_id.sb_workflow_item_ids.filtered(lambda x: x.state in ['wait_forward', 'approval']).update({'state': 'return', 'approval_instructions': 'ECR自动拒绝'})
                if apply.order_type and not apply.sale_order_id.mrp_production_ids:
                    # if apply.order_type == 'cancel':
                    #     apply.sale_order_id.action_unlock()
                    #     apply.sale_order_id.with_context(disable_cancel_warning=True, ecr_apply=True).action_cancel()
                    #     apply.sale_order_id.sb_workflow_item_ids.filtered(lambda x: x.state in ['wait_forward', 'approval']).write({'state': 'return'})
                    if apply.order_type == 'close':
                        apply.sale_order_id.action_unlock()
                        apply.sale_order_id.status = 'closed'
                    elif apply.order_type == 'hold':
                        apply.sale_order_id.action_unlock()
                        apply.sale_order_id.action_suspend_order()
                        apply.sale_order_id.status = 'hold'
                    else:
                        apply._lock_order()
                elif apply.order_type and apply.order_type == 'close':
                    apply.sale_order_id.action_unlock()
                    apply.sale_order_id.status = 'closed'
                else:
                    # 审批通过，锁定相关单据
                    apply._lock_order()
            if apply.apply_type not in ['change_info_01', 'change_info_02']: return
            vals = []
            for line in apply.line_ids:
                message_body = Markup('<ul><br/>')
                line_val = {
                    'sale_order_id': line.sale_order_id.id,
                    'order_line_id': line.order_line.id,
                    'product_id': line.order_line.product_id.id,
                    'apply_id': apply.id
                }
                order_line = line.order_line.with_context(ecr_apply=True)
                # 修改单价
                if line.c_price_unit >= 0 and line.c_price_unit != line.price_unit:
                    line_val['origin_price'] = line.price_unit
                    line_val['target_price'] = line.c_price_unit
                    order_line.price_unit = line.c_price_unit
                # 修改nre，如果原NRE不存在，修改了NRE，则需创建NRE行
                if line.nre == 0 and line.c_nre > 0:
                    self.env['sale.order.line'].sudo().create({
                        'order_id': line.sale_order_id.id,
                        'product_template_id': self.env.ref('sb_sale.nre_server_product').id,
                        'product_id': self.env.ref('sb_sale.nre_server_product').product_variant_id.id,
                        'product_uom_qty': 1,
                        'price_unit': line.c_nre,
                        'name': 'NRE',
                    })
                    message_body += Markup('<li>Origin NRE 【%s】 --> Target NRE 【%s】\n </li><br/>') % (
                        line.nre, line.c_nre)

                # 如果原NRE存在，修改了NRE，则需修改NRE行
                if 0 < line.nre != line.c_nre >= 0:
                    nre_line = line.sale_order_id.order_line.filtered(lambda x: x.product_id.detailed_type == 'service')
                    if nre_line:
                        nre = nre_line[0]
                        line_val['origin_nre'] = line.nre
                        line_val['target_nre'] = line.c_nre
                        line.sale_order_id.s_nre = line.c_nre
                        nre.price_unit = line.c_nre
                        message_body += Markup('<li>Origin NRE 【%s】 --> Target NRE 【%s】\n </li><br/>') % (
                            line.nre, line.c_nre)
                    # line.sale_order_id.message_post(body=message_body)
                if line.c_version:
                    line_val['origin_rev'] = line.pn.version
                    line_val['target_rev'] = line.c_version
                    message_body += Markup('<li>Origin PN REV 【%s】 --> Target PN REV 【%s】\n </li><br/>') % (
                        line.pn.version, line.c_version)
                    order_line.s_customer_item_code.version = line.c_version
                if line.c_pn_desc:
                    line_val['origin_pn_desc'] = line.pn_desc
                    line_val['target_pn_desc'] = line.c_pn_desc
                    message_body += Markup('<li>Origin PN Desc 【%s】 --> Target PN Desc 【%s】\n </li><br/>') % (
                        line.pn_desc, line.c_pn_desc)
                    order_line.s_customer_item_code.customer_item_desc = line.c_pn_desc

                # 修改pn,
                if line.c_pn_code:
                    line_val['origin_pn'] = line.pn.id
                    line_val['target_pn_code'] = line.c_pn_code
                    message_body += Markup('<li>Origin PN 【%s】 --> Target PN 【%s】\n </li><br/>') % (
                        line.sale_order_id.pn, line.c_pn_code)
                    # message_body += Markup('<li>Origin REV 【%s】 --> Target REV 【%s】\n </li><br/>') % (
                    #     line.order_line.pn_rev, line.c_pn.version)
                    order_line.s_customer_item_code.code = line.c_pn_code
                    # line.sale_order_id.with_context(ecr_apply=True).s_customer_item_code.code = line.c_pn_code
                    # order_line.pn_rev = line.c_pn.version
                    # line.sale_order_id.message_post(body=message_body)
                if line.c_qty > 0:
                    line_val['origin_qty'] = line.qty
                    line_val['target_qty'] = line.c_qty
                    message_body += Markup('<li>Origin Qty 【%s】 --> Target Qty 【%s】\n </li><br/>') % (
                        line.qty, line.c_qty)
                    order_line.with_context(
                        ecr_apply=True).product_uom_qty = line.c_qty
                # 不从此处发起修改计划交期，因此注释
                # if line.c_planned_receiving_date:
                #     line_val['origin_date'] = line.planned_receiving_date
                #     line_val['target_date'] = line.c_planned_receiving_date
                #     message_body += Markup(
                #         '<li>Origin Delivery Date 【%s】 --> Target Delivery Date  【%s】\n </li><br/><ul>') % (
                #                         line.planned_receiving_date, line.c_planned_receiving_date)
                #     line.sale_order_id.with_context(
                #         ecr_apply=True).planned_receiving_date = line.c_planned_receiving_date

                # c_qt字段修改存在BUG，暂时不使用
                # 修复用c_qt_select字段控制时，审批后能正确判断是否修改。但有false更新为true时，会异常把单价清零，未查到原因。
                # if line.c_qt:
                #     line_val['origin_qt'] = line.s_qt
                #     line_val['target_qt'] = line.c_qt
                #     message_body += Markup('<li>Origin QTA 【%s】 --> Target QTA 【%s】\n </li><br/>') % (
                #         line.s_qt, line.c_qt)
                #     order_line.s_qt = line.c_qt
                if line.c_materiel_status:
                    line_val['origin_materiel_status'] = line.s_materiel_status
                    line_val['target_materiel_status'] = line.c_materiel_status
                    message_body += Markup(
                        '<li>Origin Product Status 【%s】 --> Target Product Status【%s】\n </li><br/>') % (
                                        line.s_materiel_status, line.c_materiel_status)
                    order_line.s_materiel_status = line.c_materiel_status
                    order_line.product_template_id.materiel_status = line.c_materiel_status
                if line.c_special_order_type:
                    line_val['target_special_order_type'] = line.special_order_type
                    line_val['origin_special_order_type'] = line.c_special_order_type
                    message_body += Markup(
                        '<li>Origin Special type 【%s】 --> Target special type  【%s】\n </li><br/><ul>') % (
                                        line.special_order_type, line.c_special_order_type)
                    line.sale_order_id.with_context(
                        ecr_apply=True).special_order_type = line.c_special_order_type if line.c_special_order_type != 'nothing' else None
                if line.c_note:
                    message_body = 'Origin Note 【%s】 --> Target Note 【%s】\n ' % (line.note, line.c_note)
                    line.sale_order_id.message_post(body=message_body)
                    line.sale_order_id.note = line.c_note
                    line_val['origin_note'] = line.note
                    line_val['target_note'] = line.c_note
                if line.c_po:
                    message_body = 'Origin PO 【%s】 --> Target PO 【%s】\n ' % (line.po, line.c_po)
                    line.sale_order_id.message_post(body=message_body)
                    line.sale_order_id.po = line.c_po
                    line_val['origin_po'] = line.po
                    line_val['target_po'] = line.c_po
                if line.c_commitment_date:
                    # 客户交期
                    line_val['origin_commitment_date'] = line.commitment_date
                    line_val['target_commitment_date'] = line.c_commitment_date
                    message_body += Markup(
                        '<li>Origin Commitment Date 【%s】 --> Target Commitment Date  【%s】\n </li><br/><ul>') % (
                                        line.commitment_date, line.c_commitment_date)
                    line.sale_order_id.with_context(
                        ecr_apply=True).commitment_date = line.c_commitment_date
                line.sale_order_id.message_post(body=message_body)
                vals.append(line_val)
            apply.create_cache(vals)
            if s_:
                apply.sale_order_id.locked = True
        if workflow.workflow_type == 'lock_erp':
            self._erp_unlock(workflow)
        return True

    def _erp_unlock(self, workflow):
        record = workflow.s_erp_lock_id
        if record.is_lock_order and record.is_unlock_apply:
            # 锁下单
            if record.customer_ids and not record.product_tmpl_ids:
                for customer in record.customer_ids:
                    for product in customer.product_tmpl_ids:
                        product.s_disable_order = False
            elif record.product_tmpl_ids:
                for product in record.product_tmpl_ids:
                    product.s_disable_order = False

        if record.is_lock_lot:
            # 锁下卡
            if record.product_tmpl_ids and not record.sale_order_ids:
                for product in record.product_tmpl_ids:
                    product.s_disable_down_card = False
            elif record.sale_order_ids:
                for sale in record.sale_order_ids:
                    sale.is_lock = False
            elif record.customer_ids and not record.product_tmpl_ids:
                for customer in record.customer_ids:
                    for product in customer.product_tmpl_ids:
                        product.s_disable_down_card = False

        if record.is_lock_workorder:
            if record.production_id:
                mrp_prods = record.production_id
                mrp_prods |= record._get_child_mrp(record.production_id)
                mrp_prods.write({'is_lock': False})
            elif record.sale_order_ids:
                record.sale_order_ids.write({'is_lock': False})
                # self.sale_order_ids.order_line.mapped('s_mrp_production_ids').write({'is_lock': True})
                s_mrp_production_ids = record.sale_order_ids.order_line.mapped('s_mrp_production_ids')
                mrp_prods = s_mrp_production_ids
                for mrp in s_mrp_production_ids:
                    mrp_prods |= record._get_parent_mrp(mrp)
                    mrp_prods |= record._get_child_mrp(mrp)
                # 锁定工单
                for mrp in mrp_prods:
                    mrp.filtered(lambda x: x.state != 'done').is_lock = False
                    mrp.filtered(lambda x: x.state != 'done').lock_reason = record.note
                # self.sale_order_ids.order_line.mapped('s_mrp_production_ids').mapped('workorder_ids').write({'is_lock': True})
            elif record.product_tmpl_ids:
                record.product_tmpl_ids.write({'s_disable_workorder': False})

        if record.is_lock_delivery:
            if record.production_id:
                record.production_id.write({'s_disable_delivery': False})
            elif record.sale_order_ids:
                record.sale_order_ids.write({'s_disable_delivery': False})
            elif record.product_tmpl_ids:
                record.product_tmpl_ids.write({'s_disable_delivery': True})

    def _update_unlock_product(self):
        # 审批通过解锁
        workflow = self.sb_workflow_item_id.sb_workflow_id
        if workflow.workflow_type == 'lock_erp' and workflow.state == 'approve':
            erp_lock_id = workflow.s_erp_lock_id
            if erp_lock_id.customer_ids and not erp_lock_id.product_tmpl_ids:
                for customer in erp_lock_id.customer_ids:
                    for product in customer.product_tmpl_ids:
                        if erp_lock_id.type == 'lock_order':
                            product.s_disable_order = False
                        elif erp_lock_id.type == 'lock_lot':
                            product.s_disable_down_card = False
            elif erp_lock_id.product_tmpl_ids:
                for product in erp_lock_id.product_tmpl_ids:
                    if erp_lock_id.type == 'lock_order':
                        product.s_disable_order = False
                    elif erp_lock_id.type == 'lock_lot':
                        product.s_disable_down_card = False

    def approval_return(self):
        self.ensure_one()
        self.sb_workflow_item_id.write({
            'state': 'return',
            'approval_time': fields.Datetime.now(),
            'user_id': self.env.user.id,
            'approval_instructions': self.approval_instructions or '退回'
        })
        workflow = self.sb_workflow_item_id.sb_workflow_id
        apply = workflow.sale_change_apply_id
        apply.update({
            'is_c_nre': True,
            'is_c_price_unit': True,
            'is_c_po': True,
            'is_c_note': True,
            'is_c_pn': True,
            'is_c_qty': True,
            # 'is_c_planned_receiving_date': True,
            'is_c_version': True,
            'is_c_product_tmpl_id': True,
            # 'is_c_qt': True,
            'is_c_materiel_status': True,
            'is_c_special_order_type': True,
            'is_c_commitment_date': True
        })
        apply.message_post(body=self.approval_instructions or '退回')
